package com.zhu.salesmanagement.provider;

import com.zhu.salesmanagement.common.Actions;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

/**
 * 数据库Provider
 */

public class SalesProvider extends ContentProvider {

    private static final String TAG = "SalesProvider";

    private DatabaseHelper mDatabaseHelper;
    private static final String DATABASE_NAME = "sales.db"; //数据库名字
    private static final int DATABASE_VERSION = 5; //版本
    public static final String AUTHORITY = "com.zhu.salesmanagement.Provider"; //AUTHORITY
    public static final String PARAMETER_NOTIFY = "notify";

    public static final String TABLE_GOODS = "goodsinfo"; //CRC信息表
    public static final String TABLE_MYADDSTORES = "newaddstores"; //新增门店表
    public static final String TABLE_REMINDS = "reminds"; //提醒消息表
    public static final String TABLE_VISITEDSTORES = "visitedstores"; //拜访清单表
    public static final String TABLE_CUSTOMERS = "customers"; //客户表
    public static final String TABLE_PRODUCTCATEGORYS = "productcategorys"; //产品大类表
    public static final String TABLE_PRODUCTS = "products"; //产品表
    public static final String TABLE_PRODUCTSHELFS = "productshelfs"; //货架信息表
    public static final String TABLE_STOREPHOTOS = "storephotos"; //门店照片表
    

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        int count = db.delete(args.table, args.where, args.args);
        if (count > 0) sendNotify(uri);

        return count;
    }

	@Override
	public String getType(Uri arg0) {
		SqlArguments args = new SqlArguments(arg0, null, null);
        if (TextUtils.isEmpty(args.where)) {
            return "vnd.android.cursor.dir/" + args.table;
        } else {
            return "vnd.android.cursor.item/" + args.table;
        }
	}

	@Override
    public Uri insert(Uri uri, ContentValues initialValues) {

        SqlArguments args = new SqlArguments(uri);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        final long rowId = db.insert(args.table, null, initialValues);
        if (rowId <= 0) return null;

        uri = ContentUris.withAppendedId(uri, rowId);
        sendNotify(uri);

        return uri;
	}

	private void sendNotify(Uri uri) {
        String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
        if (notify == null || "true".equals(notify)) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
    }

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		mDatabaseHelper = new DatabaseHelper(getContext());
        return (mDatabaseHelper == null) ? false : true;
	}

	@Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {

        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(args.table);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
        result.setNotificationUri(getContext().getContentResolver(), uri);

        return result;
    }

	@Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        int count = db.update(args.table, values, args.where, args.args);
        if (count > 0) sendNotify(uri);

        return count;
    }

	public static class DatabaseHelper extends SQLiteOpenHelper {

		private Context mContext = null;
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("Create table "
                    + TABLE_GOODS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "dtaid TEXT," +
                    "storeid TEXT," +
                    "typeid TEXT," +
                    "place INTEGER NOT NULL DEFAULT -100," +
                    "floor INTEGER NOT NULL DEFAULT -100," +
                    "side INTEGER NOT NULL DEFAULT -100," +
                    "stype INTEGER NOT NULL DEFAULT -100," +
                    "dCreateDate TEXT," +
                    "goods TEXT," +
                    "jingpin TEXT," +
                    "import TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_MYADDSTORES + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "name TEXT," +
                    "type TEXT," +
                    "address TEXT," +
                    "contact TEXT," +
                    "mobile TEXT," +
                    "cid TEXT," +
                    "photo BLOB," +
                    "lat TEXT," +
                    "lng TEXT," +
                    "sp1 TEXT," +
                    "sp2 TEXT," +
                    "sp3 TEXT," +
                    "sp4 TEXT," +
                    "sp5 TEXT," +
                    "sp6 TEXT," +
                    "sp7 INTEGER," +
                    "sp8 INTEGER," +
                    "sp9 INTEGER," +
                    "sp10 INTEGER," +
                    "sp11 INTEGER," +
                    "sp12 INTEGER," +
                    "sp13 INTEGER," +
                    "sp14 TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_REMINDS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "eid TEXT," +
                    "msgid TEXT," +
                    "text TEXT," +
                    "time TEXT," +
                    "type TEXT," +
                    "cid TEXT," +
                    "eventid TEXT," +
                    "status TEXT," +
                    "deadtime TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_VISITEDSTORES + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "eid TEXT," +
                    "dtaid TEXT," +
                    "taskid TEXT," +
                    "date TEXT," +
                    "aeid TEXT," +
                    "itemno INTEGER NOT NULL DEFAULT 100," +
                    "storeid TEXT," +
                    "checkinlat TEXT," +
                    "checkinlng TEXT," +
                    "checkintime TEXT," +
                    "checkoutlat TEXT," +
                    "checkoutlng TEXT," +
                    "checkouttime TEXT," +
                    "vc INTEGER NOT NULL DEFAULT 0," +
                    "close INTEGER NOT NULL DEFAULT 0," +
                    "visit INTEGER NOT NULL DEFAULT 0" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_CUSTOMERS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "cid TEXT," +
                    "cname TEXT," +
                    "caddr TEXT," +
                    "ccontact TEXT," +
                    "ctel TEXT," +
                    "cdealtid TEXT," +
                    "vcode TEXT," +
                    "cslevel TEXT," +
                    "ctype TEXT," +
                    "clat TEXT," +
                    "clng TEXT," +
                    "iproperty INTEGER NOT NULL DEFAULT 0" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_PRODUCTCATEGORYS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "pcid TEXT," +
                    "pcname TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_PRODUCTS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "pcid TEXT," +
                    "pid TEXT," +
                    "sort INTEGER," +
                    "pname TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_PRODUCTSHELFS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "cid TEXT," +
                    "pcid TEXT," +
                    "scount TEXT," +
                    "slayer TEXT," +
                    "sarea TEXT" +
                    ");");

            db.execSQL("Create table "
                    + TABLE_STOREPHOTOS + " (" +
                    "_id INTEGER PRIMARY KEY," +
                    "sCustomerId TEXT," +
                    "sPhotoSource TEXT," +
                    "sDatingTaskActualID TEXT," +
                    "decPhotoLongitude TEXT," +
                    "decPhotoLatitude TEXT," +
                    "dShootDate TEXT," +
                    "data BLOB," +
                    "iSort INTEGER" +
                    ");");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        	if(DATABASE_VERSION != oldVersion && oldVersion == 1){
//        		if(Actions.DEBUG){
//        			Log.e("zhu","update goodsinfo");
//        		}
//        		db.beginTransaction();
//                try {
//                    db.execSQL("UPDATE goodsinfo SET floor=-100;");
//                    db.setTransactionSuccessful();
//                } catch (SQLException ex) {
//                    // Old version remains, which means we wipe old data
//                    Log.e(TAG, ex.getMessage(), ex);
//                } finally {
//                    db.endTransaction();
//                }
//        		db.execSQL("DROP TABLE IF EXISTS " + TABLE_GOODS);
//        		db.execSQL("DROP TABLE IF EXISTS " + TABLE_MYADDSTORES);
//        		db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDS);
//        		db.execSQL("DROP TABLE IF EXISTS " + TABLE_VISITEDSTORES);
//        		db.execSQL("DROP TABLE IF EXISTS " + TABLE_CUSTOMERS);
//        		db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTCATEGORYS);
//        		db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
//        		db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTSHELFS);
//        		onCreate(db);
        	}

        	if(DATABASE_VERSION != oldVersion){
        	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_GOODS);
        	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_MYADDSTORES);
        	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDS);
        	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_VISITEDSTORES);
        	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CUSTOMERS);
        	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTCATEGORYS);
        	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
        	    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTSHELFS);
        	    onCreate(db);
        	}
        }
    }

	static class SqlArguments {
        public final String table;
        public final String where;
        public final String[] args;

        SqlArguments(Uri url, String where, String[] args) {
            if (url.getPathSegments().size() == 1) {
                this.table = url.getPathSegments().get(0);
                this.where = where;
                this.args = args;
            } else if (url.getPathSegments().size() != 2) {
                throw new IllegalArgumentException("Invalid URI: " + url);
            } else if (!TextUtils.isEmpty(where)) {
                throw new UnsupportedOperationException("WHERE clause not supported: " + url);
            } else {
                this.table = url.getPathSegments().get(0);
                this.where = "_id=" + ContentUris.parseId(url);                
                this.args = null;
            }
        }

        SqlArguments(Uri url) {
            if (url.getPathSegments().size() == 1) {
                table = url.getPathSegments().get(0);
                where = null;
                args = null;
            } else {
                throw new IllegalArgumentException("Invalid URI: " + url);
            }
        }
    }
}
